<template>
  <el-dialog
    append-to-body
    :title="title"
    :visible.sync="dialogVisible"
    width="1200px"
    @close="close"
  >
    <div>
      <el-input
        v-model.trim="blood_id"
        class="wd300 mr12"
        clearable
        placeholder="血袋号"
        @input="getOne"
      >
        <template slot="prepend">血袋号：</template>
      </el-input>
      <el-button type="primary" @click="getOne">搜索</el-button>
      <div class="h12"></div>
    </div>
    <el-empty
      v-if="preDatas.length === 0"
      description="暂无任何数据"
      style="padding-top: 200px"
    />
    <div v-else>
      <fieldset>
        <legend>血液制备</legend>
        <div class="tip font-bold">
          说明：1.同一批制备的仅支持同一种大类(如：红细胞)&nbsp;&nbsp;&nbsp;&nbsp;
          2.下方复选框仅为了批量设置制备后血液成分，不影响提交结果，提交结果的时候不选择也可以提交
        </div>
        <div class="h12"></div>
        <el-table
          ref="multipleTable"
          border
          :data="preDatas"
          highlight-current-row
          stripe
          style="width: 100%"
          @row-click="setBlood"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="60"
          />
          <el-table-column
            align="center"
            label="血袋号"
            prop="id"
            width="100"
          />
          <el-table-column align="center" label="血型" prop="abo" width="80" />
          <el-table-column
            align="center"
            label="血量(U)"
            prop="capacity"
            width="100"
          />
          <el-table-column
            align="center"
            label="原血液成分"
            prop="product.name"
            show-overflow-tooltip
            width="160"
          />
          <el-table-column
            align="center"
            label="配血试管号"
            prop="tube_number"
            width="100"
          />
          <el-table-column align="center" label="制备后血液成分">
            <template #default="{ row }">
              <el-cascader
                v-model="row.product_id_path"
                clearable
                filterable
                :options="productsFilter"
                :props="props"
                :show-all-levels="false"
                size="mini"
                @change="changeProductsFilter(row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="失效时间" prop="tube_number">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.invalid_time"
                align="center"
                class="wd180"
                :picker-options="pickerOptions"
                placeholder="选择日期时间"
                size="mini"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80">
            <template #default="{ $index }">
              <el-link
                icon="el-icon-delete"
                type="danger"
                @click="handleDelete($index)"
              >
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="h12"></div>
        <div class="d-flex align-items-center">
          <span>制备后血液成分：</span>
          <el-cascader
            v-model="product_id_path"
            class="mr12"
            clearable
            filterable
            :options="productsFilter"
            :props="props"
            :show-all-levels="false"
          />
          <el-button
            v-if="preDatas.length > 0"
            class="ml12"
            icon="el-icon-document"
            :loading="loading"
            type="primary"
            @click="handleSubmit"
          >
            提交
          </el-button>
        </div>
      </fieldset>
      <div class="h24"></div>
      <fieldset v-if="form.id">
        <legend>血液信息</legend>
        <blood :blood="form" />
      </fieldset>
    </div>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { deepClone } from '@/utils'
  import Blood from './Blood'
  import { getOne } from '@/api/blood'
  import { computeDate, convertArr2Obj } from '@/utils/index'
  export default {
    components: {
      Blood,
    },
    data() {
      return {
        product_id_path: [],
        multipleSelection: [],
        loading: false,
        blood_id: '',
        activeName: 'first',
        dialogVisible: false,
        title: '血液制备',
        form: {},
        preDatas: [],
        props: { label: 'name', value: 'id' },
        rules: {
          product_id_path: [
            { required: true, trigger: 'blur', message: '血液成分必须' },
          ],
          invalid_time: [
            { required: true, trigger: 'blur', message: '失效日期必须' },
          ],
        },
        productsFilter: [],
        currentValidTime: '',
        pickerOptions: this.getPickerOptions(),
      }
    },
    computed: {
      ...mapGetters(['products']),
      productsAllObj() {
        let res = []
        this.products.forEach((item) => {
          res = res.concat(item.children)
        })
        const obj = convertArr2Obj(res, 'id')
        return obj
      },
    },
    watch: {
      product_id_path: {
        handler(newVal) {
          if (this.multipleSelection.length > 0) {
            this.multipleSelection.forEach((item) => {
              item.product_id_path = newVal
              this.changeProductsFilter(item)
            })
          } else {
            this.$baseMessage(
              '请选择要制备的记录',
              'error',
              'vab-hey-message-error'
            )
          }
        },
        deep: true,
      },
      // multipleSelection: {
      //   handler(newVal) {
      //     this.multipleSelection.forEach((item) => {
      //       console.log(item)
      //       item.product_id_path = newVal
      //       this.changeProductsFilter(item)
      //     })
      //   },
      //   deep: true,
      //   immediate: true,
      // },
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.multipleSelection.forEach((item) => {
          item.product_id_path = this.product_id_path
          this.changeProductsFilter(item)
        })
      },
      getPickerOptions() {
        let that = this
        return {
          disabledDate(time) {
            return time.getTime() > new Date(that.currentValidTime).getTime()
          },
        }
      },
      // setCurrent(e) {
      //   this.currentValidTime = e
      // },
      changeProductsFilter(row) {
        const invalid_time = deepClone(row).invalid_time
        if (row.product_id) {
          const product_id = row.product_id_path[row.product_id_path.length - 1]
          const product = this.productsAllObj[product_id]
          const hours = product.pre_hours
          if (hours > 0) {
            const res = computeDate('', 'add', 0, hours, 0, 0)
            row.invalid_time =
              new Date(res) < new Date(invalid_time) ? res : invalid_time
            console.log(res, invalid_time, res < invalid_time)
          } else {
            row.invalid_time = invalid_time
          }
        }
        this.currentValidTime =
          new Date(row.invalid_time) < new Date(invalid_time)
            ? row.invalid_time
            : invalid_time
      },
      setBlood(row) {
        this.form = deepClone(row)
      },
      close() {
        this.product_id_path = []
        this.blood_id = ''
        this.form = {}
        this.preDatas = []
        this.dialogVisible = false
        this.activeName = 'first'
        this.loading = false
      },
      show(row) {
        if (row.id) {
          this.blood_id = row.id
          this.getOne()
        }

        this.dialogVisible = true
      },
      getProductsFilter(row) {
        const productsFilter = deepClone(this.products)
        const product = this.productsAllObj[row.product_id]
        const pid = product['pid']
        this.productsFilter = []
        productsFilter.forEach((val) => {
          if (+val.id === +pid) {
            val.children = val.children.filter((cval) => {
              return (
                cval.id !== row.product_id &&
                !['悬浮红细胞', '机采血小板'].includes(cval.name)
              )
            })
            this.productsFilter.push(val)
          }
        })
      },
      handleSubmit() {
        this.loading = true
        this.$emit(
          'submit',
          this.form.id,
          this.preDatas.map((val) => {
            return {
              id: val.id,
              product_id_old: val.product_id_old,
              product_id: val.product_id_path[1],
              product_id_path: val.product_id_path,
              invalid_time: val.invalid_time,
            }
          })
        )
      },
      async getOne() {
        if (this.blood_id && this.blood_id.length >= 8) {
          const { data } = await getOne(this.blood_id)
          data.product_pid = data.product_id_path[0]
          this.form = data
          this.handleData(data)
          this.getProductsFilter(data)
        }
      },
      handleDelete(index) {
        const currentRow = this.preDatas[index]
        if (currentRow === this.form) {
          this.form.id = ''
        }
        this.preDatas.splice(index, 1)
      },
      handleData(data) {
        const idx = this.preDatas.findIndex((val) => {
          return val.id === this.blood_id
        })
        this.blood_id = ''
        if (idx === -1) {
          data.product_id_old = data.product_id
          if (this.preDatas.length > 0) {
            if (this.preDatas[0].product_pid === data.product_pid) {
              this.preDatas.push(data)
            } else {
              this.$baseMessage(
                '暂不支持同时处理多种血液成分大类',
                'error',
                'vab-hey-message-error'
              )
            }
          } else {
            this.preDatas.push(data)
          }
        } else {
          this.$baseMessage(
            '此血袋号已经在列表中',
            'error',
            'vab-hey-message-error'
          )
        }
      },
      hideLoading() {
        this.loading = false
      },
    },
  }
</script>

<style lang="scss" scoped></style>
